package Z11_20_pool;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： pang-yun
 * @date： 2021-11-20 16:09
 * 功能目的 ：用于   任务调度 线程池
 */
@Slf4j
public class SchedulePool {
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        AtomicInteger integer = new AtomicInteger(1);
        log.info("start.......");
        fixedRate(pool, integer);

    }

    private static void withFixedDelay(ScheduledExecutorService pool, AtomicInteger integer) {
        pool.scheduleWithFixedDelay(()->{
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(integer.getAndIncrement()+ "  "+ time());
                }
                ,1,3,TimeUnit.SECONDS);
    }


    //scheduleAtFixedRate
    private static void fixedRate(ScheduledExecutorService pool, AtomicInteger integer) {
        //定时任务
        pool.scheduleAtFixedRate(()->{
                    System.out.println(integer.getAndIncrement()+ "  "+ time());
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                ,1,3,TimeUnit.SECONDS);
    }


    // 延时执行任务
    private static void delayExecutor(ScheduledExecutorService pool) {
        pool.schedule(()->{
            log.info("A");
        },2, TimeUnit.SECONDS);

        pool.schedule(()->{
            log.info("B");
        },2, TimeUnit.SECONDS);
    }

    public static String time(){
        long l = System.currentTimeMillis();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        return formatter.format(LocalDateTime.now());

    }
}
